/**
 * @Description: 限时折扣
 * @author ourslookAdmin
 * @date 2019-09-03 09:52:32
 */
import React, {Fragment} from 'react';
import Modal from 'drag-modal';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Spin,
  Tag,
  TreeSelect,
  BackTop, Tooltip, Icon, DatePicker, Table, TimePicker, Switch, Tabs
} from 'antd';
import Highlighter from "react-highlight-words";
import {formatMessage, FormattedMessage} from 'umi/locale';
import moment from 'moment';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import {connect} from 'dva';
import {requestLists, requestPromise} from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import {getWebPath} from '../../../utils/request';
import uiUtils, {hasPermission, rulesReg, rulesRemote} from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import Ellipsis from "../../../components/ourslook/Ellipsis";

const { MonthPicker , RangePicker} = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class PromotionsLimitdiscount extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: {span: 5},
    wrapperCol: {span: 19},
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {title: '活动名称', dataIndex: 'title', align: 'center', sorter: false, key: 'title'},
    {
      title: '有效时间',
      dataIndex: 'startTime',
      width: 250,
      align: 'center',
      sorter: false,
      key: 'start_time',
      render: (value, record, index) => `${value}至${record.endTime}`,
    },
    {title: '限购类型', dataIndex: 'limitType', width: 150, align: 'center', sorter: false, key: 'limit_type',
      render: (value) => {
        let limitTypeName = '-';
        if (value === 0) {
          limitTypeName = '不限购';
        } else if (value === 1) {
          limitTypeName = '每人每种商品限购x件';
        } else if (value === 2) {
          limitTypeName = '每人每种商品前x件享受折扣';
        }
        return limitTypeName;
      },
    },
    {title: '限购值', dataIndex: 'limitValue', width: 80, align: 'center', sorter: false, key: 'limit_value'},
    {
      title: '活动状态',
      dataIndex: 'voStartStatus',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'vo_start_status',
      render: (value, record, index) => {
        let status = '';
        if (record.status === 1) {
          const startTime = moment(record.startTime).format('X');
          const endTime = moment(record.endTime).format('X');
          const nowTime = moment().format('X');
          if (startTime < nowTime && nowTime < endTime) {
            status = (
              <Tag style={{ cursor: 'default' }} className={styles.label_success}>
                正在进行中
              </Tag>
            );
          } else if (endTime < nowTime) {
            status = (
              <Tag style={{ cursor: 'default' }} className={styles.label_warning}>
                已结束
              </Tag>
            );
          } else if (nowTime < startTime) {
            status = (
              <Tag style={{ cursor: 'default' }} className={styles.label_primary}>
                未开始
              </Tag>
            );
          } else {
            status = (
              <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
                已失效
              </Tag>
            );
          }
        } else if (record.status === 0) {
          status = (
            <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
              已失效
            </Tag>
          );
        } else {
          status = '- -';
        }
        return status;
      },
    },
    {title: '活动标签', dataIndex: 'tag', width: 120, align: 'center', sorter: false, key: 'tag'},
    {
      title: '订单实付金额',
      dataIndex: 'voOrderTotalMoney',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'vo_order_total_money',
      render: (value, record, index) => {
        if (!value) {
          return '- -';
        }
        return value;
      },
    },
    {
      title: '付款订单数',
      dataIndex: 'voOrderTotalNum',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'vo_order_total_num',
      render: (value, record, index) => {
        if (!value) {
          return '- -';
        }
        return value;
      },
    },
    {
      title: '付款人数',
      dataIndex: 'voOrderTotalUser',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'vo_order_total_user',
      render: (value, record, index) => {
        if (!value) {
          return '- -';
        }
        return value;
      },
    },
    {title: '创建时间', dataIndex: 'createTime', width: 150, align: 'center', sorter: true, key: 'create_time'},
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      align: 'center',
      sorter: false,
      fixed: 'right',
      key: 'status',
      render: (value, record, index) => (
        <React.Fragment>
          <div>
            <Switch
              checkedChildren="上架"
              unCheckedChildren="下架"
              onChange={val => {
                this.setStateByTableColume(record, index);
                this.updateStatus(val);
              }}
              checked={value === 1}
            />
          </div>
        </React.Fragment>
      ),
    },
    {
      title: '操作',
      dataIndex: '',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('promotionslimitdiscount:update')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            hidden={!hasPermission('promotionslimitdiscount:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: PromotionsLimitdiscount.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'title',
      label: '活动名称',
      placeholder: '活动名称',
    },
    {
      type: 'SELECT',
      field: 'limitType',
      label: '限购类型',
      placeholder: '限购类型',
      list: [{ id: '', name: '请选限购类型' }],
    },
    {
      type: 'DATE_RANGE',
      field: 'startTime',
      label: '生效时间-开始',
      placeholder: ['生效时间-开始', ''],
    },
    {
      type: 'DATE_RANGE',
      field: 'endTime',
      label: '生效时间-结束',
      placeholder: ['生效时间-结束', ''],
    },
  ];

  componentDidMount() {
    this.requestList();
    this.queryLimitTypeList();
  }

  componentWillUnmount() {
  }

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({id: 'ours.curd.list.create'}), //创建
      editModel: {
        limitType:0
      },
      showList: 2,
    });
  };

  update = () => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }

    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑"/>,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  view = () => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看"/>,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({id: 'ours.curd.show-alert.confirm-delete'}), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}promotionslimitdiscount/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({id: 'ours.curd.show-alert.operate-success'}),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const promotionsLimitdiscount = Object.assign(this.state.editModel, this.editForm.props.form.getFieldsValue());

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = promotionsLimitdiscount.id == null ? '/promotionslimitdiscount/save' : '/promotionslimitdiscount/update';
        //对象删除一个属性
        //delete promotionsLimitdiscount.xxxxPros;

        promotionsLimitdiscount.startTime = promotionsLimitdiscount.timeBetween !== undefined ? `${promotionsLimitdiscount.timeBetween[0].format('YYYY-MM-DD HH:mm:ss')}` : null;
        promotionsLimitdiscount.endTime = promotionsLimitdiscount.timeBetween !== undefined ? `${promotionsLimitdiscount.timeBetween[1].format('YYYY-MM-DD HH:mm:ss')}` : null;

        promotionsLimitdiscount.limitdiscountSpecVoList = this.editForm.state.willProductList;

        const limitdiscountPeriod = this.editForm.state.limitdiscountPeriod;
        if (promotionsLimitdiscount.isShowPeriod){
          if(limitdiscountPeriod.period === 'daily'){
            if (limitdiscountPeriod.repeatTimeStartDay === undefined || limitdiscountPeriod.repeatTimeEndDay === undefined ) {
              uiUtils.showAlert('开始时间和结束时间不能为空！');
              return;
            }
            if (limitdiscountPeriod.repeatTimeEndDay <= limitdiscountPeriod.repeatTimeStartDay) {
              uiUtils.showAlert('结束时间必须大于开始时间！');
              return;
            }
            limitdiscountPeriod.repeatTimeStart = limitdiscountPeriod.repeatTimeStartDay;
            limitdiscountPeriod.repeatTimeEnd = limitdiscountPeriod.repeatTimeEndDay;
            limitdiscountPeriod.monthDay = null;
            limitdiscountPeriod.weekDays = null;
          }else if(limitdiscountPeriod.period === 'monthly'){
            if (limitdiscountPeriod.repeatTimeStartMonth === undefined || limitdiscountPeriod.repeatTimeEndMonth === undefined || limitdiscountPeriod.monthDay === undefined) {
              uiUtils.showAlert('开始时间和结束时间，天数不能为空！');
              return;
            }
            if (limitdiscountPeriod.repeatTimeEndMonth <= limitdiscountPeriod.repeatTimeStartMonth) {
              uiUtils.showAlert('结束时间必须大于开始时间！');
              return;
            }
            limitdiscountPeriod.repeatTimeStart = limitdiscountPeriod.repeatTimeStartMonth;
            limitdiscountPeriod.repeatTimeEnd = limitdiscountPeriod.repeatTimeEndMonth;
            limitdiscountPeriod.weekDays = null;
          }else if(limitdiscountPeriod.period === 'weekly'){
            if (limitdiscountPeriod.weekDays === undefined || limitdiscountPeriod.weekDays === null || limitdiscountPeriod.weekDays.length <= 0) {
              uiUtils.showAlert('必选选择星期！');
              return;
            }
            if (limitdiscountPeriod.repeatTimeStartWeek === undefined || limitdiscountPeriod.repeatTimeEndWeek === undefined ) {
              uiUtils.showAlert('开始时间和结束时间不能为空！');
              return;
            }
            if (limitdiscountPeriod.repeatTimeEndWeek <= limitdiscountPeriod.repeatTimeStartWeek) {
              uiUtils.showAlert('结束时间必须大于开始时间！');
              return;
            }
            limitdiscountPeriod.repeatTimeStart = limitdiscountPeriod.repeatTimeStartWeek;
            limitdiscountPeriod.repeatTimeEnd = limitdiscountPeriod.repeatTimeEndWeek;
            limitdiscountPeriod.monthDay = null;

            //转化weekDays
            let weekDays = '';
            for (let i = 0; i < limitdiscountPeriod.weekDays.length; i += 1) {
              let item = '';
              if(i === limitdiscountPeriod.weekDays.length-1){
                item = limitdiscountPeriod.weekDays[i];
              }else{
                item = `${limitdiscountPeriod.weekDays[i]},`;
              }
              weekDays += item;
            }
            limitdiscountPeriod.weekDays = weekDays;
          }
        }
        promotionsLimitdiscount.promotionsLimitdiscountPeriodEntity = limitdiscountPeriod;
        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: promotionsLimitdiscount,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({id: 'ours.curd.show-alert.operate-success'}),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!promotionsLimitdiscount.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = id => {
    requestPromise(getWebPath(`promotionslimitdiscount/info/${id}`), {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const promotionsLimitdiscount = res.promotionsLimitdiscount;
        const limitdiscountPeriod = promotionsLimitdiscount.promotionsLimitdiscountPeriodEntity === undefined ? {} : promotionsLimitdiscount.promotionsLimitdiscountPeriodEntity;

        let isShowDay = false;
        let isShowMonth = true;
        let isShowWeek = true;
        if (promotionsLimitdiscount.isShowPeriod && limitdiscountPeriod !== undefined){
          if(limitdiscountPeriod.period === 'daily'){
            limitdiscountPeriod.repeatTimeStartDay = limitdiscountPeriod.repeatTimeStart;
            limitdiscountPeriod.repeatTimeEndDay = limitdiscountPeriod.repeatTimeEnd;
            limitdiscountPeriod.monthDay = undefined;
            limitdiscountPeriod.weekDays = undefined;
            isShowDay = false;
            isShowMonth = true;
            isShowWeek = true;
          }else if(limitdiscountPeriod.period === 'monthly'){
            limitdiscountPeriod.repeatTimeStartMonth = limitdiscountPeriod.repeatTimeStart;
            limitdiscountPeriod.repeatTimeEndMonth = limitdiscountPeriod.repeatTimeEnd;
            limitdiscountPeriod.weekDays = undefined;
            isShowDay = true;
            isShowMonth = false;
            isShowWeek = true;
          }else if(limitdiscountPeriod.period === 'weekly'){
            limitdiscountPeriod.repeatTimeStartWeek = limitdiscountPeriod.repeatTimeStart;
            limitdiscountPeriod.repeatTimeEndWeek = limitdiscountPeriod.repeatTimeEnd;
            limitdiscountPeriod.monthDay = undefined;
            //转化weekDays
            if(limitdiscountPeriod.weekDays !== undefined){
              const weekDayStrs = limitdiscountPeriod.weekDays.split(",");
              const weekDays = [];
              for (let i = 0; i < weekDayStrs.length; i += 1) {
                // eslint-disable-next-line radix
                weekDays.push(parseInt(weekDayStrs[i]));
              }
              limitdiscountPeriod.weekDays = weekDays;
            }
            isShowDay = true;
            isShowMonth = true;
            isShowWeek = false;
          }
        }
        this.editForm.setState({
          isShowDay,
          isShowMonth,
          isShowWeek,
          limitdiscountPeriod,
          limitdiscountSpecVoList: promotionsLimitdiscount.limitdiscountSpecVoList,
          willProductList: promotionsLimitdiscount.limitdiscountSpecVoList
        });
        if(promotionsLimitdiscount.limitValue !== undefined){
          promotionsLimitdiscount.limitValue = `${promotionsLimitdiscount.limitValue}`;
        }
        if (promotionsLimitdiscount.startTime !== undefined && promotionsLimitdiscount.endTime !== undefined) {
          promotionsLimitdiscount.timeBetween = `${promotionsLimitdiscount.startTime}至${promotionsLimitdiscount.endTime}`;
        }
        this.setState({
          editModel: promotionsLimitdiscount
        });
      }
    });
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  operateByIds = (status) => {
  };

  //========其他所有的处理方法，请在按照约定进行处理==========


  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}promotionslimitdiscount/list`, this.params);
  };

  queryLimitTypeList = () => {
    const newRecommended = [
      { id: '', name: '请选择限购类型' },
      { id: '0', name: '不限购' },
      { id: '1', name: '每人每种商品限购x件' },
      { id: '2', name: '每人每种商品前x件享受折扣' },
    ];
    const formItem = this.findFormListItemByField('limitType');
    formItem.list = newRecommended;
  };

  updateStatus = val => {
    const {selectedRows} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    let status;
    if (val) {
      status = 1;
    } else {
      status = 0;
    }
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    this.setState({
      loading: true,
    });
    const data = {
      modelIds: ids.join(','),
      status,
    };
    requestPromise(`${getWebPath()}promotionslimitdiscount/operatePromotionsLimitdiscountByIds`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: data,
    }).then(res => {
      this.setState({
        loading: false,
      });
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({id: 'ours.curd.show-alert.operate-success'}),
          'success'
        );
        this.requestList();
      }
    });
  };

  vShow = showListNum => ({display: this.state.showList === showListNum ? 'block' : 'none'});

  render() {
    const btnStyle = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{...this.vShow(1)}}
          className={styles.oursCard}
          bodyStyle={{padding: '20px'}}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('promotionslimitdiscount:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增"/>
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...btnStyle}
              onClick={this.del}
              hidden={!hasPermission('promotionslimitdiscount:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除"/>
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{x: 1650}}
            />
          </div>
        </Card>

        <BackTop/>

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
            this.state.showList === 1 ? null : (
              <Card
                title={this.state.editModalTitle}
                bordered={false}
                actions={[
                  <div>
                    <React.Fragment>
                      <Button
                        type="primary"
                        hidden={this.state.editModalType === 'view'}
                        style={{marginRight: '18px'}}
                        onClick={this.saveOrUpdate}
                      >
                        <FormattedMessage id="ours.curd.add.save" defaultMessage="保存"/>
                      </Button>
                      <Button
                        style={{marginRight: '18px'}}
                        onClick={() => {
                          this.editForm.props.form.resetFields();
                          this.setState({showList: 1});
                        }}
                      >
                        <FormattedMessage id="ours.curd.add.back" defaultMessage="返回"/>
                      </Button>
                    </React.Fragment>
                  </div>,
                ]}
                style={{...this.vShow(2)}}
                bodyStyle={{padding: '20px'}}
                ref={node => {
                  this.container = node;
                }}
              >
                <EditForm
                  type={this.state.editModalType}
                  model={this.state.editModel}
                  wrappedComponentRef={inst => {
                    this.editForm = inst;
                  }}
                />
              </Card>
            )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default PromotionsLimitdiscount;

/**
 * 添加商品
 */
/*@Form.create()
class ProductAddForm extends React.Component {
  static propTypes = {
    visible: PropTypes.bool,
    onCancel: PropTypes.func,
    onOk: PropTypes.func,
    limitdiscountSpecVoList: PropTypes.object,
  };

  static defaultProps = {
    visible: false,
    onCancel: () => {},
    onOk: () => {},
    limitdiscountSpecVoList: []
  };

  constructor(props) {
    super(props);
    this.state = {};
    this.productSearch();
  }

  productSearch = () => {
    const productIds = [];

    if (this.props.limitdiscountSpecVoList) {
      const limitdiscountSpecVoList = this.props.limitdiscountSpecVoList;
      for (let i = 0; i < limitdiscountSpecVoList.length; i += 1) {
        productIds.push(limitdiscountSpecVoList[i].productId);
      }
    }

    requestPromise(getWebPath(`/mailproduct/list?status=2&not_IN_pre_sale=1&seckillProductIds=${productIds}`), {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const datas = res.page.list || [];
        const results = [
          <Option key="" value="">
            {'请选择商品'}
          </Option>,
        ];
        datas.forEach(r => {
          results.push(
            <Option key={r.id} value={r.id}>
              {r.productName}
            </Option>
          );
        });
        this.setState({
          productOptions: results,
        });
      }
    });
  };

  requestSpecList = productId => {
    requestPromise(
      `${getWebPath(
        `/mailproductspec/list?productId=${productId === undefined ? '' : productId}`
      )}`,
      {
        method: 'GET',
      }
      // eslint-disable-next-line consistent-return
    ).then(res => {
      if (res && res.code === 0) {
        const results = res.page.list;
        const datas = [];
        results.forEach(r => {
          const data = {
            key: r.id,
            name: this.specsParse(r.productSpecs),
            value: r.productSpecs,
            price: r.price,
          };
          datas.push(data);
        });

        const specDataOptions = [
          <Option key="" value="">
            请选择规格
          </Option>,
        ];
        datas.forEach(r => {
          specDataOptions.push(
            <Option key={r.key} value={r.key}>
              规格：{r.name}--价格：{r.price}
            </Option>
          );
        });

        this.setState({
          // eslint-disable-next-line object-shorthand
          specDataOptions: specDataOptions,
        });
        return datas;
      }
    });
  };

  /!**
   * 解析规格
   * @param specs
   *!/
  specsParse = specs => {
    if (specs === null || specs === undefined) {
      return '默认规格';
    }
    const productSpecs = JSON.parse(specs);
    let productss = '';
    productSpecs.forEach(s => {
      // eslint-disable-next-line guard-for-in,no-restricted-syntax
      for (const key in s) {
        productss = productss === '' ? s[key] : `${productss},${s[key]}`;
      }
    });
    return productss;
  };

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  render() {
    const visible = this.props.visible;
    const onCancel = this.props.onCancel;
    const onOk = this.props.onOk;
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px

    return (
      <Modal
        title="添加商品"
        width={1000}
        visible={visible}
        onCancel={() => {
          onCancel();
        }}
        onOk={() => {
          this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
              const limitdiscountSpec = Object.assign(model, this.props.form.getFieldsValue());
              limitdiscountSpec.productName = this.state.productName;
              limitdiscountSpec.price = this.state.price;
              onOk(limitdiscountSpec);
            }
          });
        }}
      >
        <Card bordered bodyStyle={{ paddingBottom: 10 }} style={{ marginBottom: 20 }}>
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="请选择商品" {...formItemLayout}>
                {getFieldDecorator('productId', {
                  initialValue: '',
                  rules: [
                    {
                      required: true,
                      message: '商品必填',
                    },
                  ],
                })(
                  <Select
                    showSearch
                    style={{ width: 460 }}
                    placeholder="请选择商品"
                    optionFilterProp="children"
                    onChange={(value, option) => {
                      this.setState({ productName: option.props.children });
                      this.props.form.setFieldsValue({ specId: null });
                      if (!(value === undefined || value === null || value === '')) {
                        this.requestSpecList(value);
                      }
                    }}
                    notFoundContent={null}
                  >
                    {this.state.productOptions}
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="请选择规格" {...formItemLayout}>
                {getFieldDecorator('specId', {
                  rules: [
                    {
                      required: true,
                      message: '规格必填',
                    },
                  ],
                })(
                  <Select
                    showSearch
                    style={{ width: 300 }}
                    placeholder="请选择规格"
                    optionFilterProp="children"
                    notFoundContent={null}
                    onChange={(value, option) => {
                      if (option.props.children.length === 4) {
                        this.setState({ price: option.props.children[3] });
                      }
                    }}
                  >
                    {this.state.specDataOptions}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="打折" {...formItemLayout}>
                {getFieldDecorator('discountRate', {
                  initialValue: model.discountRate,
                  rules: [
                    {
                      required: true,
                      message: '请输入打折',
                    },
                    rulesReg('nozero'),
                    rulesReg('plusnums5'),
                  ],
                })(
                  <Input
                    style={{ width: '300px' }}
                    placeholder="打折，如：0至10之间"
                    onBlur={e => {
                      if(e.target.value !== undefined){
                        this.props.form.setFieldsValue({
                          reducePrice: this.state.price !== undefined ? (this.state.price * (10-e.target.value) * 0.1).toFixed(2) : "",
                          amountPrice: this.state.price !== undefined ? (this.state.price * e.target.value * 0.1).toFixed(2) : ""
                        });
                      }
                    }}
                  />)}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="减价" {...formItemLayout}>
                {getFieldDecorator('reducePrice', {
                  initialValue: model.reducePrice,
                  rules: [
                    {
                      required: true,
                      message: '请输入减价',
                    },
                    rulesReg('nozero'),
                    rulesReg('money_0_999999'),
                  ],
                })(
                  <Input
                    style={{ width: '300px' }}
                    placeholder="减价"
                    onBlur={e => {
                      if(e.target.value !== undefined){
                        this.props.form.setFieldsValue({
                          discountRate: this.state.price !== undefined ? (10-e.target.value/0.1/this.state.price).toFixed(1): "",
                          amountPrice: this.state.price !== undefined ? (this.state.price - e.target.value).toFixed(2): ""
                        });
                      }
                    }}
                  />)}
                <Tooltip
                  placement="right"
                  title="减价=原价*（10-折扣）*0.1"
                >
                  <Icon type="question-circle" />
                </Tooltip>
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="最终价格" {...formItemLayout}>
                {getFieldDecorator('amountPrice', {
                  initialValue: model.amountPrice,
                  rules: [
                    {
                      required: true,
                      message: '请输入最终价格',
                    },
                    rulesReg('nozero'),
                    rulesReg('money_0_999999'),
                  ],
                })(
                  <Input
                    style={{ width: '300px' }}
                    placeholder="最终价格"
                    onBlur={e => {
                      if(e.target.value !== undefined ){
                        this.props.form.setFieldsValue({
                          discountRate: this.state.price !== undefined ? (e.target.value / 0.1 / this.state.price ).toFixed(2): "",
                          reducePrice: this.state.price !== undefined ? (this.state.price - e.target.value).toFixed(2): ""
                        });
                      }
                    }}
                  />)}
                &nbsp;&nbsp;
                <Tooltip
                  placement="right"
                  title="最终价格=原价*折扣*0.1"
                >
                  <Icon type="question-circle" />
                </Tooltip>
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="排序" {...formItemLayout}>
                {getFieldDecorator('sort', {
                  initialValue: model.sort,
                  rules: [
                    {
                      required: true,
                      message: '排序必填',
                    },
                    rulesReg('plus'),
                  ],
                })(
                  <Input
                    style={{ width: '300px' }}
                    type="text"
                    maxLength={9}
                    autocomplete="off"
                    placeholder="排序"
                  />
                )}
              </FormItem>
            </Col>
          </Row>
        </Card>
      </Modal>
    );
  }
}*/

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {

  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
  };

  constructor(props) {
    super(props);
    this.productSearch();
    this.state = {
      limitdiscountSpecVoList:[],
      limitdiscountPeriod:{},
      monthList:this.getMonthList(),
      weekDayList:[
        {id: 1, name: '周一'},
        {id: 2, name: '周二'},
        {id: 3, name: '周三'},
        {id: 4, name: '周四'},
        {id: 5, name: '周五'},
        {id: 6, name: '周六'},
        {id: 0, name: '周日'}
      ],
      isShowDay:false,
      isShowMonth:false,
      isShowWeek:false,
      willProductList:[]
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  productSearch = () => {
    const limitdiscountId = this.props.model.id === undefined ? null : this.props.model.id;
    requestPromise(getWebPath(`/mailproduct/listData?status=2&not_IN_limit_discount=1`), {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const datas = res.mailProductList || [];
        this.setState({
          productLists: datas,
        });
      }
    });
  };

  getMonthList = () => {
    const monthList = [];
    for (let i = 1; i < 32; i += 1) {
      monthList.push({ id: i, name: i });
    }
    return monthList;
  };

  getLimitTypeName = limitType => {
    let limitTypeName = '';
    if (limitType === 0) {
      limitTypeName = '不限购';
    } else if (limitType === 1) {
      limitTypeName = '每人每种商品限购x件';
    } else if (limitType === 2) {
      limitTypeName = '每人每种商品前x件享受折扣';
    }
    return limitTypeName;
  };

  /*showProductAddFrom = () => {
    this.setState({ productAddFromVisible: true });
  };*/

  delSeckillProduct = index => {
    let datasources = this.state.limitdiscountSpecVoList;
    if (datasources === undefined) {
      datasources = [];
    }
    const newdataSources = [];
    datasources.forEach((value, index1) => {
      if (index1 !== index) {
        newdataSources.push(datasources[index1]);
      }
    });
    this.setState({
      limitdiscountSpecVoList: newdataSources,
    });
  };

  saveProduct = item => {
    item.isCanjia = true;
    const { willProductList:newWillProductList } = this.state;
    const newItem = {productId:item.id,specId:item.specId,productName:item.productName,price:item.price,sort:1};
    newWillProductList.push(newItem);
    this.setState({
      willProductList: newWillProductList,
    });
  };

  delProduct = (item,index) => {
    const { willProductList:newWillProductList,productLists:newProductLists } = this.state;
    newWillProductList.splice(index, 1);
    for (let i = 0; i < newProductLists.length; i += 1) {
      if(newProductLists[i].id === item.productId && newProductLists[i].specId === item.specId){
        newProductLists[i].isCanjia = false;
        newProductLists[i].isCancelCanjia = false;
        break;
      }
    }
    this.setState({
      willProductList: newWillProductList,
      productLists: newProductLists,
    });
  };

  cancelProduct = item => {
    item.isCanjia = false;
    item.isCancelCanjia = false;
    const { willProductList:newWillProductList } = this.state;
    for (let i = 0; i < newWillProductList.length; i += 1) {
      if(newWillProductList[i].productId === item.id  && newWillProductList[i].specId === item.specId){
        newWillProductList.splice(i, 1);
        break;
      }
    }
    this.setState({
      willProductList: newWillProductList,
    });
  };

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder="商品名称"
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          查询
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => (
      <Highlighter
        highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  });

  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys ,willSaveProduct: selectedRows});
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {form, form: {getFieldDecorator, getFieldValue, setFieldsValue}} = this.props;
    const periodModel = this.state.limitdiscountPeriod;
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 18}, //5+19=24,少一个栅格
    };
    const colSpanLayout1 = {md: 5, sm: 24}; //每一col跨?列
    const colSpanLayout = {md: 12, sm: 24}; //每一col跨?列
    const rowGutterPxLayout = {md: 24, sm: 16}; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    const format = 'HH:mm:ss';
    const columns = [
      {
        title: '商品名称',
        dataIndex: 'productName',
        key: 'productName',
        ...this.getColumnSearchProps('productName'),
      },
      {
        title: '商品原价',
        dataIndex: 'price',
        key: 'price',
        width:100,
      },
      {
        title: '操作',
        key: '',
        dataIndex: '',
        width: 100,
        fixed: 'right',
        render: (value, record, index) => (
          <React.Fragment>
            {
              record.isCanjia !== true &&
              <a
                onClick={() => {
                  this.saveProduct(record);
                }}
              >
                参加折扣
              </a>
            }
            {
              record.isCanjia === true && record.isCancelCanjia !== true &&
              <span>已参加</span>
            }
            {
              record.isCancelCanjia === true &&
              <a
                onClick={() => {
                  this.cancelProduct(record);
                }}
                style={{ color: 'red' }}
              >
                取消参加
              </a>
            }
          </React.Fragment>
        ),
      },
    ];
    const willProductColumns = [
      {
        title: '商品名称',
        dataIndex: 'productName',
        key: 'productName',
        render: value => (
          <Ellipsis length={50} tooltip>
            {value}
          </Ellipsis>
        )
      },
      {
        title: '商品原价',
        dataIndex: 'price',
        key: 'price',
        width:100,
      },
      {
        title: '打折',
        dataIndex: 'discountRate',
        key: 'discountRate',
        width:100,
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            {getFieldDecorator(`discountRate-${index}`, {
              rules: [
                {
                  required: true,
                  message: '请输入打折',
                },
                rulesReg('nozero'),
                rulesReg('plusnums5'),
              ],
              initialValue: recode.discountRate !== undefined &&  recode.discountRate !== null ? Number.parseFloat(recode.discountRate).toFixed(1) : recode.discountRate,
            })(
              <Input
                placeholder="打折"
                style={{ width: '70px' }}
                onBlur={e => {
                  if(e.target.value !== undefined && e.target.value !== ""){
                    recode.discountRate = e.target.value;
                    recode.reducePrice = recode.price !== undefined ? (recode.price * (10-e.target.value) * 0.1).toFixed(2) : "";
                    recode.amountPrice = recode.price !== undefined ? (recode.price * e.target.value * 0.1).toFixed(2) : "";

                    this.props.form.setFieldsValue({
                      [`reducePrice-${index}`]: recode.reducePrice,
                      [`amountPrice-${index}`]: recode.amountPrice,
                    });
                  }
                }}
              />
            )}
          </FormItem>
        )
      },
      {
        title: '减价',
        dataIndex: 'reducePrice',
        key: 'reducePrice',
        width:100,
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            {getFieldDecorator(`reducePrice-${index}`, {
              rules: [
                {
                  required: true,
                  message: '请输入减价',
                },
                rulesReg('nozero'),
                rulesReg('money_0_999999'),
              ],
              initialValue: recode.reducePrice,
            })(
              <Input
                placeholder="减价"
                style={{ width: '70px' }}
                onBlur={e => {
                  if(e.target.value !== undefined  && e.target.value !== ""){
                    recode.reducePrice = e.target.value;
                    recode.discountRate = recode.price !== undefined ? (10-e.target.value/0.1/recode.price).toFixed(1): "";
                    recode.amountPrice = recode.price !== undefined ? (recode.price - e.target.value).toFixed(2): "";

                    this.props.form.setFieldsValue({
                      [`discountRate-${index}`]: recode.discountRate,
                      [`amountPrice-${index}`]: recode.amountPrice,
                    });
                  }
                }}
              />
            )}
          </FormItem>
        )
      },
      {
        title: '最终价格',
        dataIndex: 'amountPrice',
        key: 'amountPrice',
        width:100,
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            {getFieldDecorator(`amountPrice-${index}`, {
              rules: [
                {
                  required: true,
                  message: '请输入最终价格',
                },
                rulesReg('nozero'),
                rulesReg('money_0_999999'),
              ],
              initialValue: recode.amountPrice,
            })(
              <Input
                placeholder="最终价格"
                style={{ width: '80px' }}
                onBlur={e => {
                  if(e.target.value !== undefined  && e.target.value !== ""){
                    recode.amountPrice = e.target.value;
                    recode.discountRate = recode.price !== undefined ? (e.target.value / 0.1 / recode.price ).toFixed(1): "";
                    recode.reducePrice = recode.price !== undefined ? (recode.price - e.target.value).toFixed(2): "";

                    this.props.form.setFieldsValue({
                      [`discountRate-${index}`]: recode.discountRate,
                      [`reducePrice-${index}`]: recode.reducePrice,
                    });
                  }
                }}
              />
            )}
          </FormItem>
        )
      },
      {
        title: '操作',
        key: '',
        dataIndex: '',
        width: 100,
        fixed: 'right',
        render: (value, record, index) => (
          <a
            onClick={() => {
              this.delProduct(record,index);
            }}
          >
            取消折扣
          </a>
        ),
      },
    ];
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Fragment>
        <Form layout="horizontal">
          <Row gutter={{...rowGutterPxLayout}}>
            <Col {...colSpanLayout}>
              <FormItem label="活动名称" {...formItemLayout}>
                {type === 'view'
                  ? model.title
                  : getFieldDecorator('title', {
                    initialValue: model.title,
                    rules: [
                      {
                        required: true,
                        message: '活动名称必填',
                      },
                      {
                        max: 64,
                        message: '最长64个字符',
                      },
                    ],
                  })(
                    <Input
                      type="text"
                      autocomplete="off"
                      placeholder="活动名称"
                    />
                  )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="生效时间" {...formItemLayout}>
                {type === 'view'
                  ? model.timeBetween
                  : getFieldDecorator('timeBetween', {
                    initialValue: [
                      model.startTime === undefined || model.startTime === ''? '': moment(model.startTime, 'YYYY-MM-DD HH:mm:ss'),
                      model.endTime === undefined || model.endTime === ''? '': moment(model.endTime, 'YYYY-MM-DD HH:mm:ss')
                    ],
                    rules: [
                      {
                        required: true,
                        message: '生效时间必选',
                      },
                    ],
                  })(
                    <RangePicker
                      style={{ width: 330 }}
                      showTime
                      placeholder={['请选择生效开始时间', '请选择生效结束时间']}
                      defaultValue={[
                        model.startTime === undefined || model.startTime === ''? '': moment(model.startTime, 'YYYY-MM-DD HH:mm:ss'),
                        model.endTime === undefined || model.endTime === ''? '': moment(model.endTime, 'YYYY-MM-DD HH:mm:ss')
                      ]}
                    />
                  )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{...rowGutterPxLayout}}>
            <Col {...colSpanLayout}>
              <FormItem label="活动标签" {...formItemLayout}>
                {type === 'view'
                  ? model.tag
                  : getFieldDecorator('tag', {
                    initialValue: model.tag,
                    rules: [
                      {
                        required: true,
                        message: '活动标签必填',
                      },
                      {
                        max: 32,
                        message: '最长32个字符',
                      }
                    ],
                  })(
                    <Input
                      type="text"
                      autocomplete="off"
                      placeholder="活动标签"
                    />
                  )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="限购类型" {...formItemLayout}>
                {type === 'view'
                  ? this.getLimitTypeName(model.limitType)
                  : getFieldDecorator('limitType', {
                    initialValue: model.limitType,
                    rules: [
                      {
                        required: true,
                        message: '限购类型必选',
                      },
                    ],
                  })(
                    <Select
                      style={{ width: '100%' }}
                      onChange={value => {
                        model.limitType = value;
                      }}
                    >
                      <option value={0}>不限购</option>
                      <option value={1}>每人每种商品限购x件</option>
                      <option value={2}>每人每种商品前x件享受折扣</option>
                    </Select>
                  )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{...rowGutterPxLayout}}>
            {
              (model.limitType === 1 || model.limitType === 2) &&
              <Col {...colSpanLayout}>
                <FormItem label="限购值" {...formItemLayout}>
                  {type === 'view'
                    ? model.limitValue
                    : getFieldDecorator('limitValue', {
                      initialValue: model.limitValue,
                      rules: [
                        {
                          required: true,
                          message: '限购值必填',
                        },
                        {
                          max: 9,
                          message: '最长9个字符',
                        },
                        rulesReg('plus'),
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        placeholder="限购值"
                      />
                    )}
                </FormItem>
              </Col>
            }
          </Row>
          <Card
            bordered
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20 }}
            title="高级设置"
          >
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...colSpanLayout}>
                <FormItem label="按周期重复" {...formItemLayout}>
                  {getFieldDecorator('isShowPeriod', {
                    initialValue: model.isShowPeriod,
                  })(
                    <Checkbox
                      checked={model.isShowPeriod}
                      onChange={e => {
                        model.isShowPeriod = e.target.checked;
                        if(model.isShowPeriod){
                          periodModel.period = "daily";
                          this.setState({
                            isShowDay: false,
                            isShowMonth: true,
                            isShowWeek:true
                          });
                        }
                      }}
                      disabled={type === 'view'}
                    >
                      按周期重复
                    </Checkbox>
                  )}
                  &nbsp;&nbsp;
                  <Tooltip
                    placement="right"
                    title="每进入一个新的周期，限购数量刷新，如：此处选择了每周周一限购1件，则同一用户每周一均可购买1件。"
                  >
                    <Icon type="question-circle" />
                  </Tooltip>
                </FormItem>
              </Col>
            </Row>
            {
              model.isShowPeriod === true &&
              <Col {...colSpanLayout} style={{marginLeft: 100}}>
                <FormItem {...formItemLayout}>
                  {getFieldDecorator('period', {
                    initialValue: periodModel.period,
                  })(
                    <RadioGroup
                      disabled={type === 'view'}
                      onChange={e => {
                        periodModel.period = e.target.value;
                        if(periodModel.period === 'daily'){
                          this.setState({
                            isShowDay: false,
                            isShowMonth: true,
                            isShowWeek:true
                          });
                          this.props.form.setFieldsValue({
                            repeatTimeStartMonth:undefined,
                            repeatTimeEndMonth: undefined,
                            repeatTimeStartWeek:undefined,
                            repeatTimeEndWeek: undefined,
                            weekDays: undefined,
                            monthDay: undefined
                          });
                        }else if(periodModel.period === 'monthly'){
                          this.setState({
                            isShowDay: true,
                            isShowMonth: false,
                            isShowWeek:true
                          });
                          this.props.form.setFieldsValue({
                            repeatTimeStartDay:undefined,
                            repeatTimeEndDay: undefined,
                            repeatTimeStartWeek:undefined,
                            repeatTimeEndWeek: undefined,
                            weekDays: undefined,
                          });
                        } else if(periodModel.period === 'weekly'){
                          this.setState({
                            isShowDay: true,
                            isShowMonth: true,
                            isShowWeek: false
                          });
                          this.props.form.setFieldsValue({
                            repeatTimeStartDay:undefined,
                            repeatTimeEndDay: undefined,
                            repeatTimeStartMonth:undefined,
                            repeatTimeEndMonth: undefined,
                            monthDay: undefined
                          });
                        }
                      }}
                    >
                      <Radio value="daily">
                        每天
                        {getFieldDecorator('repeatTimeStartDay', {
                          initialValue: periodModel.repeatTimeStartDay === undefined || periodModel.repeatTimeStartDay === '' || periodModel.repeatTimeStartDay === null ? '' : moment(periodModel.repeatTimeStartDay, format),
                        })(
                          <TimePicker
                            disabled={this.state.isShowDay === true || type === 'view'}
                            defaultValue={periodModel.repeatTimeStartDay === undefined || periodModel.repeatTimeStartDay === '' || periodModel.repeatTimeStartDay === null ? '' : moment(periodModel.repeatTimeStartDay, format)}
                            format={format}
                            onChange={(value, valueStr) => {
                              periodModel.repeatTimeStartDay = valueStr;
                            }}
                          />
                        )}
                        至
                        {getFieldDecorator('repeatTimeEndDay', {
                          initialValue: periodModel.repeatTimeEndDay === undefined || periodModel.repeatTimeEndDay === '' || periodModel.repeatTimeEndDay === null ? '' : moment(periodModel.repeatTimeEndDay, format),
                        })(
                          <TimePicker
                            disabled={this.state.isShowDay === true || type === 'view'}
                            defaultValue={periodModel.repeatTimeEndDay === undefined || periodModel.repeatTimeEndDay === '' || periodModel.repeatTimeEndDay === null ? '' : moment(periodModel.repeatTimeEndDay, format)}
                            format={format}
                            onChange={(value, valueStr) => {
                              periodModel.repeatTimeEndDay = valueStr;
                            }}
                          />
                        )}
                      </Radio>
                      <br />
                      <Radio value="monthly">
                        每月
                        {getFieldDecorator('monthDay', {
                          initialValue: periodModel.monthDay,
                        })(
                          <Select
                            style={{ width: '100px' }}
                            placeholder="请选择"
                            onChange={value => {
                              periodModel.monthDay = value;
                            }}
                            disabled={this.state.isShowMonth === true || type === 'view'}
                          >
                            {uiUtils.getOptionList(this.state.monthList)}
                          </Select>
                        )}
                        {getFieldDecorator('repeatTimeStartMonth', {
                          initialValue: periodModel.repeatTimeStartMonth === undefined || periodModel.repeatTimeStartMonth === '' || periodModel.repeatTimeStartMonth === null ? '' : moment(periodModel.repeatTimeStartMonth, format),
                        })(
                          <TimePicker
                            defaultValue={periodModel.repeatTimeStartMonth === undefined || periodModel.repeatTimeStartMonth === '' || periodModel.repeatTimeStartMonth === null ? '' : moment(periodModel.repeatTimeStartMonth, format)}
                            format={format}
                            onChange={(value, valueStr) => {
                              periodModel.repeatTimeStartMonth = valueStr;
                            }}
                            disabled={this.state.isShowMonth === true || type === 'view'}
                          />
                        )}
                        至
                        {getFieldDecorator('repeatTimeEndMonth', {
                          initialValue: periodModel.repeatTimeEndMonth === undefined || periodModel.repeatTimeEndMonth === '' || periodModel.repeatTimeEndMonth === null ? '' : moment(periodModel.repeatTimeEndMonth, format),
                        })(
                          <TimePicker
                            defaultValue={periodModel.repeatTimeEndMonth === undefined || periodModel.repeatTimeEndMonth === '' || periodModel.repeatTimeEndMonth === null ? '' : moment(periodModel.repeatTimeEndMonth, format)}
                            format={format}
                            onChange={(value, valueStr) => {
                              periodModel.repeatTimeEndMonth = valueStr;
                            }}
                            disabled={this.state.isShowMonth === true || type === 'view'}
                          />
                        )}
                      </Radio>
                      <br />
                      <Radio value="weekly">
                        每周
                        {getFieldDecorator('weekDays', {
                          initialValue: periodModel.weekDays,
                        })(
                          <Select
                            placeholder="请选择"
                            mode="multiple"
                            disabled={this.state.isShowWeek === true || type === 'view'}
                            onChange={value => {
                              periodModel.weekDays = value;
                            }}
                          >
                            {uiUtils.getOptionList(this.state.weekDayList)}
                          </Select>
                        )}
                        {getFieldDecorator('repeatTimeStartWeek', {
                          initialValue: periodModel.repeatTimeStartWeek === undefined || periodModel.repeatTimeStartWeek === '' || periodModel.repeatTimeStartWeek === null ? '' : moment(periodModel.repeatTimeStartWeek, format),
                        })(
                          <TimePicker
                            defaultValue={periodModel.repeatTimeStartWeek === undefined || periodModel.repeatTimeStartWeek === '' || periodModel.repeatTimeStartWeek === null ? '' : moment(periodModel.repeatTimeStartWeek, format)}
                            format={format}
                            onChange={(value, valueStr) => {
                              periodModel.repeatTimeStartWeek = valueStr;
                            }}
                            disabled={this.state.isShowWeek === true || type === 'view'}
                          />
                        )}
                        至
                        {getFieldDecorator('repeatTimeEndWeek', {
                          initialValue: periodModel.repeatTimeEndWeek === undefined || periodModel.repeatTimeEndWeek === '' || periodModel.repeatTimeEndWeek === null ? '' : moment(periodModel.repeatTimeEndWeek, format),
                        })(
                          <TimePicker
                            defaultValue={periodModel.repeatTimeEndWeek === undefined || periodModel.repeatTimeEndWeek === '' || periodModel.repeatTimeEndWeek === null ? '' : moment(periodModel.repeatTimeEndWeek, format)}
                            format={format}
                            onChange={(value, valueStr) => {
                              periodModel.repeatTimeEndWeek = valueStr;
                            }}
                            disabled={this.state.isShowWeek === true || type === 'view'}
                          />
                        )}
                      </Radio>
                      <br />
                    </RadioGroup>
                  )}
                </FormItem>
              </Col>
            }
          </Card>
          <Card
            bordered
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20 }}
            title="参加活动的商品"
          >
            <Tabs style={{ marginTop: '20px' }} defaultActiveKey="0">
              <Tabs.TabPane tab="第一步：选择商品" key="0">
                <Table
                  onRow={(record) => ({
                    onMouseEnter: () => {
                      if(record.isCanjia === true){
                        record.isCancelCanjia = true;
                      }
                    },
                    onMouseLeave: () => {
                      if(record.isCanjia === true){
                        record.isCancelCanjia = false;
                      }
                    },
                  })}
                  rowSelection={rowSelection}
                  columns={columns}
                  dataSource={this.state.productLists}
                  size="small"
                />
                <Button
                  type="primary"
                  onClick={() => {
                    const { willSaveProduct:newWillSaveProduct ,productLists:newProductLists,willProductList:newWillProductList} = this.state;
                    if(newWillSaveProduct !== undefined && newWillSaveProduct.length>0){
                      for (let i = 0; i < newProductLists.length; i += 1) {
                        for (let j = 0; j < newWillSaveProduct.length; j += 1) {
                          if(newProductLists[i].id === newWillSaveProduct[j].id && newProductLists[i].isCanjia !== true){
                            newProductLists[i].isCanjia = true;
                            const newItem = {productId:newProductLists[i].id,specId:newProductLists[i].specId,productName:newProductLists[i].productName,price:newProductLists[i].price,sort:1};
                            newWillProductList.push(newItem);
                          }
                        }
                      }
                      this.setState({
                        productLists:newProductLists,
                        willProductList:newWillProductList
                      });
                    }else{
                      uiUtils.showMessage(`请先批量选择商品！`, 'info');
                    }
                  }}
                >批量参加</Button>
              </Tabs.TabPane>
              <Tabs.TabPane tab="第二步：设置折扣" key="1">
                <Row gutter={{ ...rowGutterPxLayout }} style={{left:170}}>
                  {
                    this.state.isAllAccount !== true &&
                    <Col {...colSpanLayout1}>
                      <Button
                        style={{ marginTop: '3px' }}
                        onClick={() => {
                          model.discountRate = undefined;
                          this.props.form.setFieldsValue({
                            discountRate: undefined
                          });
                          this.setState({
                            isAllAccount:true
                          });
                        }}
                      >
                        全部打折
                      </Button>
                    </Col>
                  }
                  {
                    this.state.isAllAccount === true &&
                    <Col {...colSpanLayout1}>
                      <FormItem style={{ marginBottom: '0px' }}>
                      {getFieldDecorator('discountRate', {
                        initialValue: model.discountRate,
                        rules: [
                          {
                            required: true,
                            message: '请输入打折',
                          },
                          rulesReg('nozero'),
                          rulesReg('plusnums5'),
                        ],
                      })(
                        <Input
                          style={{ width: '50px',height:'32px' }}
                          placeholder="打折"
                          onChange={(e) => {
                            model.discountRate = e.target.value;
                          }}
                        />)}
                      <a
                        style={{ marginLeft: 10 }}
                        onClick={() => {
                          if(model.discountRate !== undefined || model.discountRate !== ""){
                            const discountRate = model.discountRate;
                            const { willProductList:newWillProductList } = this.state;
                            for (let i = 0; i < newWillProductList.length; i += 1) {
                              newWillProductList[i].discountRate = discountRate;
                              newWillProductList[i].reducePrice = newWillProductList[i].price !== undefined ? (newWillProductList[i].price * (10-discountRate) * 0.1).toFixed(2) : "";
                              newWillProductList[i].amountPrice = newWillProductList[i].price !== undefined ? (newWillProductList[i].price * discountRate * 0.1).toFixed(2) : "";
                              this.props.form.setFieldsValue({
                                [`discountRate-${i}`]: newWillProductList[i].discountRate,
                                [`reducePrice-${i}`]:  newWillProductList[i].reducePrice,
                                [`amountPrice-${i}`]:  newWillProductList[i].amountPrice,
                              });
                            }
                            this.setState({
                              willProductList:newWillProductList
                            });
                          }
                          this.setState({
                            isAllAccount:false
                          });
                        }}
                      >
                        确定
                      </a>
                      <a
                        style={{ marginLeft: 10 }}
                        onClick={() => {
                          this.setState({
                            isAllAccount:false
                          });
                        }}
                      >
                        取消
                      </a>
                      </FormItem>
                    </Col>
                  }
                  {
                    this.state.isAllReduce !== true &&
                    <Col {...colSpanLayout1}>
                      <Button
                        style={{ marginTop: '3px' }}
                        onClick={() => {
                          model.reducePrice = undefined;
                          this.props.form.setFieldsValue({
                            reducePrice: undefined
                          });
                          this.setState({
                            isAllReduce:true
                          });
                        }}
                      >
                        全部减价
                      </Button>
                    </Col>
                  }
                  {
                    this.state.isAllReduce === true &&
                    <Col {...colSpanLayout1}>
                      <FormItem style={{ marginBottom: '0px' }}>
                      {getFieldDecorator('reducePrice', {
                        initialValue: model.reducePrice,
                        rules: [
                          {
                            required: true,
                            message: '请输入减价',
                          },
                          rulesReg('nozero'),
                          rulesReg('money_0_999999'),
                        ],
                      })(
                        <Input
                          style={{ width: '50px',height:'32px' }}
                          placeholder="减价"
                          onChange={(e) => {
                            model.reducePrice = e.target.value;
                          }}
                        />)}
                      <a
                        style={{ marginLeft: 10 }}
                        onClick={() => {
                          if(model.reducePrice !== undefined && model.reducePrice !== ""){
                            const reducePrice = model.reducePrice;
                            const { willProductList:newWillProductList } = this.state;
                            for (let i = 0; i < newWillProductList.length; i += 1) {
                              newWillProductList[i].reducePrice = reducePrice;
                              newWillProductList[i].discountRate = newWillProductList[i].price !== undefined ? (10-reducePrice/0.1/newWillProductList[i].price).toFixed(1): "";
                              newWillProductList[i].amountPrice = newWillProductList[i].price !== undefined ? (newWillProductList[i].price - reducePrice).toFixed(2): "";
                              this.props.form.setFieldsValue({
                                [`reducePrice-${i}`]: newWillProductList[i].reducePrice,
                                [`discountRate-${i}`]:  newWillProductList[i].discountRate,
                                [`amountPrice-${i}`]:  newWillProductList[i].amountPrice,
                              });
                            }
                            this.setState({
                              willProductList:newWillProductList
                            });
                          }
                          this.setState({
                            isAllReduce:false
                          });
                        }}
                      >
                        确定
                      </a>
                      <a
                        style={{ marginLeft: 10 }}
                        onClick={() => {
                          this.setState({
                            isAllReduce:false
                          });
                        }}
                      >
                        取消
                      </a>
                      </FormItem>
                    </Col>
                  }
                </Row>
                <Table
                  style={{ marginTop: 10 }}
                  columns={willProductColumns}
                  bordered
                  dataSource={this.state.willProductList}
                />
              </Tabs.TabPane>
            </Tabs>
            {/*{type !== 'view' && (
              <Row gutter={{ ...rowGutterPxLayout }}>
                <Button
                  style={{ marginLeft: 10 }}
                  type="primary"
                  icon="plus"
                  onClick={this.showProductAddFrom}
                >
                  添加商品
                </Button>
              </Row>
            )}
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Table
                style={{ marginTop: 10 }}
                columns={columns}
                bordered
                dataSource={this.state.limitdiscountSpecVoList}
              />
            </Row>*/}
          </Card>
        </Form>
        {/*<ProductAddForm
          key={Math.random()}
          visible={this.state.productAddFromVisible}
          limitdiscountSpecVoList={this.state.limitdiscountSpecVoList}
          onCancel={() => {
            this.productAddForm.props.form.resetFields();
            this.setState({ productAddFromVisible: false });
          }}
          onOk={limitdiscountSpec => {
            // eslint-disable-next-line react/no-access-state-in-setstate
            let datasources = this.state.limitdiscountSpecVoList;
            if (datasources === undefined) {
              datasources = [];
            }
            datasources.push(limitdiscountSpec);
            this.setState({
              limitdiscountSpecVoList: datasources,
            });
            this.setState({
              productAddFromVisible: false,
            });
          }}
          wrappedComponentRef={inst => {
            this.productAddForm = inst;
          }}
        />*/}
      </Fragment>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
